package com.hm.common.common;

import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 * @author shishun.wang
 * @date 10:44:31 AM Dec 11, 2015
 * @version 1.0
 * @describe 模板引擎引入
 */
public class FtlFactoryUtil {

	private Template template;

	// 默认模板存放位置
	private String rootPath;

	public FtlFactoryUtil rootDirectory(String rootDirectory) {
		this.rootPath = rootDirectory;
		return this;
	}

	@SuppressWarnings("deprecation")
	public FtlFactoryUtil build(String fileName) throws Exception {
		Configuration configuration = new Configuration();
		configuration.setClassForTemplateLoading(FtlFactoryUtil.class, rootPath);
		configuration.setDefaultEncoding("UTF-8");
		this.template = configuration.getTemplate(fileName);
		return this;
	}

	public String process(Map<String, String> mapper) throws Exception {
		ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
		Writer out = new OutputStreamWriter(byteStream);
		this.template.process(mapper, out);

		return new String(byteStream.toByteArray());
	}

	public void process(Map<String, String> mapper, Writer out) throws Exception {
		this.template.process(mapper, out);
	}

}